﻿using System;
using System.Diagnostics;

namespace MikeKappel.Com.CS
{
    public static partial class SortingAlgorithms
    {
        public delegate Boolean CountingDelegate(Int32 currentIndex, Int32 currentValue);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="onSort">On value change method to fire</param>
        /// <param name="ittems">Array of Integers to sort</param>
        public static void CountingSort(Int32[] items, CountingDelegate onSort)
        {

            Int32 maximum = Int32.MinValue;
            Int32 minimum = Int32.MaxValue;
            for (Int32 i = 0; i < items.Length; i++)
            {
                if (onSort != null && !onSort(i, items[i]))
                    goto escape;

                if (items[i] > maximum)
                    maximum = items[i];

                if (items[i] < minimum)
                    minimum = items[i];
            }

            Int32 range = maximum - minimum + 1;
            Int32[] bucket = new Int32[range];      
            for (Int32 i = 0; i < items.Length; i++)
            {
                bucket[items[i] - minimum]++;
                if (onSort != null && !onSort(i, items[i]))
                    goto escape;
            }

            Int32 index = 0;
            for (Int32 i = minimum; i <= maximum; i++)
                for (Int32 j = 0; j < bucket[i - minimum]; j++)
                {
                    if (onSort != null && !onSort(i, items[i]))
                        goto escape;

                    items[index++] = i;
                }
        escape:
            return;

        }
        public static void CountingSort(Int32[] items)
        {
            CountingSort(items, null);
        }
    }
}
